package com.jiawa.train.gateWay.Filter;


import com.jiawa.train.gateWay.properties.JwtProperties;
import com.jiawa.train.gateWay.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class LoginMemberFilter implements GlobalFilter{

    @Resource
    private JwtProperties jwtProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        // OPTIONS 请求放行
        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
            return chain.filter(exchange);
        }

        if(path.contains("/admin")
            || path.contains("/member/member/login")
            || path.contains("/member/member/sendCode")
            || path.contains("/member/hello")
            || path.contains("/business/hello")
            || path.contains("/business/kaptcha/imageCode/")){
            return chain.filter(exchange);
        }else{
            log.info("需要验证{}",path);
        }
        //获取header的token参数
        String token = exchange.getRequest().getHeaders().getFirst(jwtProperties.getAdminTokenName());
        //当token为空时，返回错误
        if(token == null || token.isEmpty()){
            //返回错误的状态码并且结束执行
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //当token不为空时，进行验证
        try {
            Claims claims = JWTUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            log.info("用户信息: {}", claims);
            String memberId = claims.get("id").toString();
            log.info("用户id: {}", memberId);
            // 可在此将 memberId放入请求头中传递给下游服务
            ServerWebExchange swe = exchange.mutate()
                    .request(builder -> builder.header("MemberId", memberId))
                    .build();
            return chain.filter(swe);
        } catch (Exception e) {
            log.warn("JWT解析失败: {}", e.getMessage());
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
}
